package com.chapter.sample.answer.exporter;

import com.chapter.sample.answer.exporter.annotations.MethodExporter;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class MethodExporterAspect {
    //容器捞鱼，谁带着使用了MethodExporter注解将回触发Around业务逻辑
    @Around("@annotation(com.chapter.sample.answer.exporter.annotations.MethodExporter)")
    public Object methodExporter(ProceedingJoinPoint joinPoint) throws Throwable {

        Object retVal = null;
        long startTime = System.currentTimeMillis();
        log.info("-----@Around环绕通知AAA-methodExporter");
        retVal = joinPoint.proceed();//放行
        long endTime = System.currentTimeMillis();
        long costTime = startTime - endTime;

        //1、获取重载后的方法名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        //2、确定方法名后获取得该方法上面配置的注解标签MyRedisCache
        MethodExporter methodExporterAnnotation = method.getAnnotation(MethodExporter.class);
        if (methodExporterAnnotation != null) {
            //3、获得方法里面的形参信息
            StringBuffer jsonInputParam = new StringBuffer();
            Object[] args = joinPoint.getArgs();
            DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
            //ParameterNameDiscoverer discoverer = new StandardReflectionParameterNameDiscoverer();
            String[] parameterNames = discoverer.getParameterNames(method);
            for (int i = 0; i < parameterNames.length; i++) {
                jsonInputParam.append(parameterNames[i] + args[i] + ";");
            }
            //4、将返回结果retValue序列化
            String jsonResult = null;
            if (retVal != null) {
                jsonResult = new ObjectMapper().writeValueAsString(retVal);
            } else {
                jsonResult = "null";
            }
            log.info("\n方法分析上报中,类名方法名:" + joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature() +
                    "\n执行耗时:" + costTime + "毫秒" +
                    "\n输入参数：" + jsonInputParam +
                    "\n返回结果：" + jsonResult + "" +
                    "\nover");
            log.info("--------@Aroud环绕通知BBB-methodExporter");
        }
        return retVal;
    }
}
